/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package src;

import java.util.HashMap;
import java.util.Set;
import java.io.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Login extends HttpServlet{
    
    public void doGet(HttpServletRequest request, HttpServletResponse response){
        processar(request,response);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response){
        processar(request,response);
    }

    private void processar(HttpServletRequest request, HttpServletResponse response) {
       try{
			listaUsuarios listaObj = new listaUsuarios();
			HashMap<String, Usuario> listaUser = new HashMap<>();
			Usuario user = null;
			String url = "";
			//*****************Carrega do arquivo para sessão**********************
			HttpSession session = request.getSession();
			if(session.getAttribute("listaObj")==null){
				try {
					FileInputStream fis = new FileInputStream("usuarios.obj");
					ObjectInputStream ois = new ObjectInputStream(fis);
					listaObj = (listaUsuarios) ois.readObject();
					session.setAttribute("listaObj", listaObj);
				} catch (Exception e) {
				}
			}else{
				listaObj = (listaUsuarios) session.getAttribute("listaObj");
			}
			//*********************************************************************
			
			listaUser = listaObj.getListaUsuarios();
			user = listaUser.get(request.getParameter("email"));
			if(user == null){
				url = "erro.jsp?erro=ERRO: Usuario inexistente";
			}
			else{
				if(user.getSenha().equals(request.getParameter("senha"))){
					url = "home.jsp";
					session.setAttribute("userAtual", user);
				}else{
					url = "erro.jsp?erro=ERRO: Senha incorreta";
				}
			}
			
			RequestDispatcher dispatcher = request.getRequestDispatcher(url);
			dispatcher.forward(request, response);
			
		}catch(Exception e){
            e.printStackTrace();
		}
    }
}